import React,{useEffect,useState} from 'react'
import { BorderBox7,BorderBox12,BorderBox8,BorderBox13} from '@jiaminghi/data-view-react'
import * as THREE from 'three'
import {
    LeftOutlined,
    RightOutlined,
  } from '@ant-design/icons';
import { Row, Col, PageHeader } from 'antd';

import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import Stats from 'three/examples/jsm/libs/stats.module.js';
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
import { ThreeMFLoader } from 'three/examples/jsm/loaders/3MFLoader.js';
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js';
import { ConvexGeometry } from "three/examples/jsm/geometries/ConvexGeometry"
// import ThreeBSP from "../../../3dScreen/common/ThreeBSP.js"

// import Stats from './jsm/libs/stats.module.js';
// import { OrbitControls } from './jsm/controls/OrbitControls.js';
// import { RoomEnvironment } from './jsm/environments/RoomEnvironment.js';
// import { GLTFLoader } from './jsm/loaders/GLTFLoader.js';
// import { DRACOLoader } from './jsm/loaders/DRACOLoader.js';

import './threeDemo.less'

let rayCaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();

const ThreeBSP = require('jthreebsp')(THREE)
var camera, scene, renderer, stats,docDom,width,height,marginLeft,marginTop;

export default function ThreeDemo() {
    const [tagTop, setTagTop] = useState(0);
    const [tagLeft, setTagLeft] = useState(0)
    const [isShowTag, setIsShowTag] = useState(false);

    useEffect(() => {
        docDom =  document.getElementById('container');
        width = docDom.clientWidth;
        height = docDom.clientHeight;
        let rect = docDom.getBoundingClientRect();

        marginTop = rect.top - docDom.clientTop;
        marginLeft = rect.left - docDom.clientLeft;

        fnFbxLoading();
        // fnGear();
    }, []);

    let fnInitCamera = ()=>{
        camera = new THREE.PerspectiveCamera( 45, width / height, 1, 2000 );
        camera.position.set( 0, 1200, 0 );
    }

    let fnInitScene = ()=>{
        scene = new THREE.Scene();
    }

    let fnInitLight = ()=>{
         // scene.background = new THREE.Color( 0xa0a0a0 );
            // scene.fog = new THREE.Fog( 0xa0a0a0, 200, 1000 );

            const hemiLight = new THREE.HemisphereLight( 0xffffff, 0x444444 );
            hemiLight.position.set( 0, 200, 0 );
            scene.add( hemiLight );

            // const dirLight = new THREE.DirectionalLight( 0xffffff );
            // dirLight.position.set( 0, 200, 100 );
            // dirLight.castShadow = true;
            // dirLight.shadow.camera.top = 180;
            // dirLight.shadow.camera.bottom = - 100;
            // dirLight.shadow.camera.left = - 120;
            // dirLight.shadow.camera.right = 120;
            // scene.add( dirLight );

            // const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2000, 2000 ), new THREE.MeshPhongMaterial( { color: 0x999999, depthWrite: false } ) );
            // mesh.rotation.x = - Math.PI / 2;
            // mesh.receiveShadow = true;
            // scene.add( mesh );

            // const grid = new THREE.GridHelper( 2000, 20, 0x000000, 0x000000 );
            // grid.material.opacity = 0.2;
            // grid.material.transparent = true;
            // scene.add( grid );
    }

    let fnRenderer = ()=>{
        renderer = new THREE.WebGLRenderer( { antialias: true } );
        // renderer.setPixelRatio( window.devicePixelRatio );
        renderer.setSize( width, height );
        renderer.shadowMap.enabled = true;
        docDom.appendChild( renderer.domElement );
    }

    let fnControls = ()=>{
        const controls = new OrbitControls( camera, renderer.domElement );
        controls.target.set( 0, 100, 0 );
        controls.update();

        window.addEventListener( 'resize', onWindowResize );
        // stats
        // stats = new Stats();
        // docDom.appendChild( stats.dom );
    }

    let fnClickRayCaster = (event) => {
        console.log(marginTop,marginLeft);
        console.log(event.clientY,event.clientX);

        console.log(event.clientY - marginTop,event.clientX - marginLeft);

        // mouse.x = ((event.clientX - marginLeft) / width) * 2 - 1;
        // mouse.y = -((event.clientY - marginTop) / height) * 2 + 1;

        mouse.x = ((event.clientX - marginLeft) / width) * 2 - 1;
        mouse.y = -((event.clientY - marginTop) / height) * 2 + 1;
        
        rayCaster.setFromCamera(mouse, camera);
        
        let child = [];
        let children = scene.children[1];
        children.children.forEach(function(mesh){
                if(mesh.type == "Mesh"){
                    let userData =  mesh.userData;
                    let userColor = userData.color;
                    if(userColor){
                        mesh.material.color.setRGB(userColor.r,userColor.g,userColor.b);
                    }
                    child.push(mesh);
                }
            }
        );
        let intersects=rayCaster.intersectObjects(child);
        if(!intersects.length){
            setIsShowTag(false);
        }else{
            setTagLeft(event.clientX-marginLeft);
            setTagTop(event.clientY-marginTop-145);
            setIsShowTag(true);
        }
        for (var i = 0; i < intersects.length; i++) {
            let intersect = intersects[i].object;
            intersect.material.color.set(0x07a9e6);
        }
    }

    let onWindowResize = ()=> {

        docDom =  document.getElementById('container');
        width = docDom.clientWidth;
        height = docDom.clientHeight;
        let rect = docDom.getBoundingClientRect();

        marginTop = rect.top;
        marginLeft = rect.left;

        camera.aspect = width / height;
        camera.updateProjectionMatrix();

        docDom.addEventListener( 'click', fnClickRayCaster, false );

        renderer.setSize( width, height );

        window.location.reload();

    }

    let fnFbxLoading = ()=>{
        const clock = new THREE.Clock();
        let mixer;
        fnInitCamera();
        fnInitScene();
        fnInitLight();

        const loader = new FBXLoader();
        loader.load( './models/gear.fbx', function ( object ) {

            mixer = new THREE.AnimationMixer( object );

            let animations = object.animations;

            animations.map((animation)=>{
                const action = mixer.clipAction( animation );
                action.play();
            });

            object.traverse( function ( child ) {
                if ( child.isMesh ) {
                    child.castShadow = true;
                    child.receiveShadow = true;
                }
            } );
            scene.add( object );

            let children = scene.children[1];
            children.children.forEach(function(mesh){
                    if(mesh.type == "Mesh"){
                        let color = mesh.material.color;
                        let userData =  mesh.userData;
                        if(!mesh.userData.color){
                            userData.color = {r:color.r,g:color.g,b:color.b};
                        }
                    }
                }
            );
        } );
        
        fnRenderer();
        fnControls();
        animate();
        docDom.addEventListener( 'click', fnClickRayCaster, false );

        function animate() {
            requestAnimationFrame( animate );
            const delta = clock.getDelta();
            if ( mixer ) mixer.update( delta );
            renderer.render( scene, camera );
            // stats.update();
        }
    }

    let fnSetCamera = (face)=>{
        let length = camera.position.length();
        if(face == "up"){
            var vec3 = new THREE.Vector3(1, 1, 1).normalize();
            camera.position.set(vec3.x * length, vec3.y * length, vec3.z * length);
        }else if(face == "left"){
            camera.position.set(0, 0, length);
        }else if(face == "right"){
            camera.position.set(0, length, 0);
        }else if(face == "front"){
            camera.position.set(-length, 0, 0);
        }
        camera.lookAt(scene.position);
        renderer.render( scene, camera );
    }

    return (
        <div className="three-demo-view">
            <BorderBox12 color={['#1a1d2f', '#1a1d2f']}>
                <div id="container" style={{width:"95%",height:'95%',margin:20}}>

                </div>
            </BorderBox12>
            <div className="attr-data">
                    <Row justify="space-around">
                        <Col span={4}>
                            <BorderBox13 className="attr-data-box" color={['#2c324e']}>
                                <div className="attr-data-content">182</div>
                                <div className="attr-data-title">转速</div>
                            </BorderBox13>
                        </Col>
                        <Col span={4}>
                            <BorderBox13 className="attr-data-box" color={['#2c324e']}>
                                <div className="attr-data-content">240</div>
                                <div className="attr-data-title">电压</div>
                            </BorderBox13>
                        </Col>
                        <Col span={4}>
                            <BorderBox13 className="attr-data-box" color={['#2c324e']}>
                                <div className="attr-data-content">190</div>
                                <div className="attr-data-title">限制转速</div>
                            </BorderBox13>
                        </Col>
                        <Col span={4}>
                            <BorderBox13 className="attr-data-box" color={['#2c324e']}>
                                <div className="attr-data-content">300</div>
                                <div className="attr-data-title">限制电压</div>
                            </BorderBox13>
                        </Col>
                    </Row>
            </div>
            <div className="attr-tag">
                <BorderBox12 color={['#1a1d2f', '#1a1d2f']} className="attr-box">
                        <div>
                            设备：1000000
                        </div>
                        <div>
                            周期：2001
                        </div>
                        <div>
                            压力角α：45
                        </div>
                        <div>
                            齿数：10
                        </div>
                        <div>
                            齿宽：3
                        </div>
                </BorderBox12>
            </div>
            <div className="change-camera">
                <div onClick={()=>fnSetCamera("up")}>
                    <img src="./imgs/up.png"></img>
                </div>
                <div onClick={()=>fnSetCamera("left")}> <img src="./imgs/left.png"></img></div>
                <div onClick={()=>fnSetCamera("right")}> <img src="./imgs/right.png"></img></div>
                <div onClick={()=>fnSetCamera("front")}> <img src="./imgs/front.png"></img></div>
            </div>
            <div className="change-dev-left">
                <div onClick={()=>fnSetCamera("up")}>
                    {/* <img src="./imgs/up.png"></img> */}
                    <LeftOutlined style={{fontSize:25}} />
                </div>
            </div>
            <div className="change-dev-right">
                <div onClick={()=>fnSetCamera("up")}>
                    {/* <img src="./imgs/up.png"></img> */}
                    <RightOutlined style={{fontSize:25}}/>
                </div>
            </div>
            {
                isShowTag&&
                <div className="dev-desc" style={{top:tagTop,left:tagLeft}}>
                    <div className="dev-name">
                        设备机床
                    </div>
                    <div className="dev-tag">
                        <img src="./imgs/line1.png" width="250"></img>
                    </div>
                </div>
            }
            
        </div>
    )
}
